/*
 *  Copyright 2013 HCIWriter
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.hci.writer.client.ui;

import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.Modal;
import com.github.gwtbootstrap.client.ui.TextArea;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.hci.writer.shared.ExerciseStep;
import com.hci.writer.shared.Task;

public class WriteViewImpl extends Composite implements WriteView {

	@UiField TextArea txtInput;
	@UiField Button btnFinish;
	@UiField Modal modExplain;
	@UiField Label labExplain;
	@UiField Button btnClose;

	private static WriteViewImplUiBinder uiBinder = GWT
			.create(WriteViewImplUiBinder.class);

	interface WriteViewImplUiBinder extends UiBinder<Widget, WriteViewImpl> {
	}

	private Presenter presenter;
	
	public WriteViewImpl() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}
	
	@Override
	public void init(Task task) {
		txtInput.setText(task.oldText);
		txtInput.setFocus(true);
		if(task.steps.isEmpty()) {
			txtInput.setCursorPos(0);
		} else {
			ExerciseStep lastStep = task.steps.get(task.steps.size()-1);
			txtInput.setCursorPos(lastStep.cursor);
		}
		
		labExplain.setText(task.getHelp());
		modExplain.show();
		btnClose.setFocus(true);
	}
	
	@UiHandler("btnClose")
	void onBtnClose(ClickEvent e) {
		modExplain.hide();
	}
	
	@UiHandler("txtInput")
	void onTxtInput(KeyUpEvent e) {
		this.presenter.processKeystroke(txtInput.getValue(), txtInput.getCursorPos(), txtInput.getSelectionLength());
	}

	@UiHandler("txtInput")
	void onTxtInput(ClickEvent e) {
		this.presenter.processKeystroke(txtInput.getValue(), txtInput.getCursorPos(), txtInput.getSelectionLength());
	}

	@UiHandler("btnFinish")
	void onBtnFinish(ClickEvent e) {
		this.presenter.finishExercise();
	}
}
